﻿using System;
using System.Linq;
using System.Web.Mvc;
using CodeContrib.Web.Mvc;
using CodeContribBlog.Data;
using CodeContribBlog.Web.Mvc.ViewModels;

namespace CodeContribBlog.Web.Mvc.Controllers
{
	public class HomeController : Controller
	{
		public new User User
		{
			get
			{
				if (base.User.Identity.IsAuthenticated)
				{
					return HttpContext.Items["__User"] as User;
				}

				return null;
			}
		}

		public int UserId
		{
			get
			{
				if (User == null)
				{
					return 0;
				}

				return User.Id;
			}
		}

		[ImportModelStateFromTempData]
		public ActionResult Index()
		{
			//throw new System.Web.HttpException(500, "Testing 123.");

			var viewModel = new HomeViewModel();
			var now = DateTime.UtcNow;

			using (var blogContext = new BlogContext())
			{
				viewModel.PublicBlogs = blogContext.Blogs
					.Select(b => new BlogViewModel
						             {
							             Creator = b.Creator.Name,
							             PostCount = b.Posts.Where(x => !x.IsDeleted && x.PublishedAt <= now).Count(),
							             Subtitle = b.Subtitle,
							             Title = b.Title,
							             Url = b.Url
						             }).ToList();
			}

			using (var blogContext = new BlogContext(UserId))
			{
				viewModel.UserBlogs = blogContext.Blogs
					.Select(b => new BlogViewModel
						             {
							             Creator = b.Creator.Name,
							             PostCount = b.Posts.Where(x => !x.IsDeleted && x.PublishedAt <= now).Count(),
							             Subtitle = b.Subtitle,
							             Title = b.Title,
							             Url = b.Url
						             }).ToList();
			}

			return View("Index", viewModel);
		}

		protected override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			base.OnActionExecuted(filterContext);

			ViewBag.User = User;
		}
	}
}